﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;

namespace AppBox.admin
{
    public partial class log : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 默认的排序列和排序方向
            Grid1.SortColumnIndex = 0;
            Grid1.SortDirection = "DESC";

            // 每页记录数
            Grid1.PageSize = XConfigHelper.PageSize;

            // 点击删除按钮时，至少选中一项
            ResolveDeleteGridItem(btnDeleteSelected, Grid1);

            BindGrid();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<XLog>();
            q.Where("1").IsEqualTo("1");

            // 在错误信息中搜索
            string searchText = ttbSearchMessage.Text.Trim();
            if (!String.IsNullOrEmpty(searchText))
            {
                q.And(XLog.MessageColumn).ContainsString(searchText);
            }

            // 过滤错误级别
            if (ddlSearchLevel.SelectedValue != "ALL")
            {
                q.And(XLog.LogLevelColumn).IsEqualTo(ddlSearchLevel.SelectedValue);
            }

            // 过滤搜索范围
            if (ddlSearchRange.SelectedValue != "ALL")
            {
                DateTime today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                switch (ddlSearchRange.SelectedValue)
                {
                    case "TODAY":
                        q.And(XLog.DatetimeXColumn).IsGreaterThanOrEqualTo(today);
                        break;
                    case "LAST3DAYS":
                        q.And(XLog.DatetimeXColumn).IsGreaterThanOrEqualTo(today.AddDays(-3));
                        break;
                    case "LAST7DAYS":
                        q.And(XLog.DatetimeXColumn).IsGreaterThanOrEqualTo(today.AddDays(-7));
                        break;
                    case "LASTMONTH":
                        q.And(XLog.DatetimeXColumn).IsGreaterThanOrEqualTo(today.AddMonths(-1));
                        break;
                    case "LASTYEAR":
                        q.And(XLog.DatetimeXColumn).IsGreaterThanOrEqualTo(today.AddYears(-1));
                        break;
                }
            }


            // 在查询添加之后，排序和分页之前获取总记录数
            // Grid1总共有多少条记录
            Grid1.RecordCount = q.GetRecordCount();


            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, XLog.Schema));

            // 数据库分页
            q.Paged(Grid1.PageIndex + 1, Grid1.PageSize);
            XLogCollection items = q.ExecuteAsCollection<XLogCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }



        #endregion

        #region Events

        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            BindGrid();
        }

        protected void ddlSearchLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void ddlSearchRange_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;

            BindGrid();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 从每个选中的行中获取Logid（在Grid1中定义的DataKeyNames）
            List<int> ids = new List<int>();
            foreach (int rowIndex in Grid1.SelectedRowIndexArray)
            {
                ids.Add(Convert.ToInt32(Grid1.DataKeys[rowIndex][0]));
            }

            // 执行数据库操作
            new Delete().From<XLog>()
                 .Where(XLog.LogidColumn).In(ids)
                 .Execute();

            // 清空当前选中的项
            Grid1.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            int id = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);

            if (e.CommandName == "Delete")
            {
                XLog.Delete(id);

                BindGrid();
            }
        }

        #endregion

    }
}
